from flask import jsonify, request, Response
from supermarket.app import app, db, redis_store
from supermarket.app.models import PurchaseMaster, PurchaseDetail
import csv
from io import StringIO

# PurchasesMaster的CRUD操作
@app.route('/purchases', methods=['GET'])
def get_purchases():
    try:
        purchases = PurchaseMaster.query.all()
        serialized_purchases = [purchase.to_dict() for purchase in purchases]
        return jsonify(serialized_purchases), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/purchases/<int:id>', methods=['GET'])
def get_purchase(id):
    try:
        purchase = PurchaseMaster.query.get_or_404(id)
        serialized_purchase = purchase.to_dict()
        return jsonify(serialized_purchase), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/purchases', methods=['POST'])
def create_purchase():
    try:
        data = request.get_json()
        new_purchase = PurchaseMaster(**data)
        db.session.add(new_purchase)
        db.session.commit()
        return jsonify(new_purchase.to_dict()), 201
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/purchases/<int:id>', methods=['PUT'])
def update_purchase(id):
    try:
        purchase = PurchaseMaster.query.get_or_404(id)
        data = request.get_json()
        for key, value in data.items():
            setattr(purchase, key, value)
        db.session.commit()
        return jsonify(purchase.to_dict()), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/purchases/<int:id>', methods=['DELETE'])
def delete_purchase(id):
    try:
        purchase = PurchaseMaster.query.get_or_404(id)
        # 删除掉其下面的一切PurchaseDetails
        details = PurchaseDetail.query.filter_by(list_id=purchase.id).all()
        for detail in details:
            db.session.delete(detail)
        # 再删除它的全部信息
        db.session.delete(purchase)
        db.session.commit()
        return jsonify({'message': 'Purchase deleted'}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


# PurchaseDetails的CRUD操作
@app.route('/purchases/<int:purchase_id>/details', methods=['GET'])
def get_purchase_details(purchase_id):
    try:
        details = PurchaseDetail.query.filter_by(list_id=purchase_id).all()
        serialized_details = [detail.to_dict() for detail in details]
        return jsonify(serialized_details), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/purchases/<int:purchase_id>/details', methods=['POST'])
def create_purchase_detail(purchase_id):
    try:
        purchase_master = PurchaseMaster.query.get_or_404(purchase_id)
        data = request.get_json()
        new_detail = PurchaseDetail(list_id=purchase_master.id,**data)
        db.session.add(new_detail)
        db.session.commit()
        return jsonify(new_detail.to_dict()), 201
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/purchases/<int:purchase_id>/details/<int:id>', methods=['PUT'])
def update_purchase_detail(purchase_id, id):
    try:
        detail = PurchaseDetail.query.filter_by(list_id=purchase_id, id=id).first()
        data = request.get_json()
        for key, value in data.items():
            setattr(detail, key, value)
        db.session.commit()
        return jsonify(detail.to_dict()), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@app.route('/purchases/<int:purchase_id>/details/<int:id>', methods=['DELETE'])
def delete_purchase_detail(purchase_id, id):
    try:
        purchasedetail = PurchaseDetail.query.get_or_404(id)
        db.session.delete(purchasedetail)
        db.session.commit()
        return jsonify({'message': 'Purchase Detail deleted'}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


# 导出采购数据到CSV报表
@app.route('/purchases/export/csv', methods=['GET'])
def export_purchases_csv():
    try:
        purchases = PurchaseMaster.query.all()

        output = StringIO()
        csv_writer = csv.writer(output)

        for purchase in purchases:
            # 写入文件头部信息和Purchase Master信息
            csv_writer.writerow(['id', 'employee_id', 'quantity', 'total_price', 'purchase_time', 'remark'])
            csv_writer.writerow([purchase.id, purchase.employee_id, purchase.quantity, purchase.total_price,
                                 purchase.purchase_time, purchase.remark])

            # 写入文件头部信息和Purchase Detail信息
            for detail in purchase.details:
                csv_writer.writerow(['id', 'list_id', 'product_id', 'quantity', 'unit_price', 'total_price', 'remark'])
                csv_writer.writerow([detail.id, detail.list_id, detail.product_id, detail.quantity, detail.unit_price,
                                     detail.total_price, detail.remark])

        output.seek(0)

        return Response(output, mimetype='text/csv', headers={'Content-Disposition': 'attachment; filename=purchases.csv'}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400
